import random

from Order import orders_count_increment, Order
from params import max_orders_per_time, max_orders_per_uav
from utils import time_now


class UnloadingPoint:
    """卸货点"""

    def __init__(self, x, y):
        self.x = x
        self.y = y

        self.id = f'UP({x:.2f}, {y:.2f})'

        # 订单列表
        self.orders_list = []

    def gen_orders(self):
        """每次增加0至2个订单"""
        n_new_orders = random.randint(0, max_orders_per_time)
        # n_new_orders = 2
        for i in range(n_new_orders):
            orders_count_increment()
            order_priority = random.randint(0, 2)
            # 每次添加的订单都按过期时间排列，过期时间越早，排在越前面
            new_order = Order(self, order_priority, time_now())
            n_orders = self.orders_num
            # 按过期时间插入队列
            flag = False
            for j in range(n_orders):
                if self.orders_list[j].expire_time > new_order.expire_time:
                    self.orders_list.insert(j, new_order)
                    flag = True
                    break
            if not flag:
                self.orders_list.append(new_order)

    @property
    def site(self):
        return tuple((self.x, self.y))

    @property
    def orders_num(self):
        """当前订单数"""
        return len(self.orders_list)

    def pop_nearest_n_orders(self):
        """输出前n个订单"""
        res = None
        if self.orders_num > max_orders_per_uav:
            res = self.orders_list[:max_orders_per_uav]
            self.orders_list = self.orders_list[max_orders_per_uav:]
        return res

    def __str__(self):
        return f'[({self.x}, {self.y}): {self.orders_list}]'

    def __repr__(self):
        return self.__str__()
